package com.theten52.demo.io.s1;

import java.io.*;
import java.net.Socket;

/**
 * 服务端收到连接请求后,处理请求的线程,阻塞式IO
 * @author wangjin
 */
public class ServerProcessThread implements Runnable {

    private Socket socket;

    public ServerProcessThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        //获取客户端的数据,并写回
        //等待响应

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = "";
            String requestStr = "";
            System.out.println("来自客户端的数据:");
            while ((line = bufferedReader.readLine()) != null) {
                requestStr += line;
                System.out.println(line);
            }
            Writer writer = new OutputStreamWriter(socket.getOutputStream());
            writer.write("data from server " + requestStr + "\r\n");
            writer.flush();
            writer.close();
            bufferedReader.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
